import { ConfigBiz } from "./ConfigBiz.js";
class HelperCore {
  static jsonFuncQueryStr(jsonRouter) {
    let jsonResult = {};
    if (jsonRouter !== null && jsonRouter !== undefined && jsonRouter.query !== null && jsonRouter.query !== undefined) {
      jsonResult = jsonRouter.query;
    }
    if (Object.keys(jsonResult).length === 0) {
      const strSearch = window.location.search;
      if (strSearch !== null && strSearch !== "") {
        //判断数据是否有效
        const strSearch2 = decodeURIComponent(strSearch);
        const strArraySearch = strSearch2.substring(1).split("&");
        for (let NumLoop = 0; NumLoop < strArraySearch.length; NumLoop++) {
          //遍历数组
          const strArraySearch2 = strArraySearch[NumLoop].split("=");
          jsonResult[strArraySearch2[0]] = strArraySearch2[1];
        }
      }
    }
    return jsonResult;
  }
  //Get URL Parameter.
  static queryStrFunc(paramName, jsonRouter) {
    let strResult = "";
    const jsonQueryStr = this.jsonFuncQueryStr(jsonRouter);
    if (jsonQueryStr !== null && this.boolFuncJsonExistChk(jsonQueryStr, paramName)) {
      //Get parameters from router.
      strResult = jsonQueryStr[paramName];
    }
    return strResult;
  }
  static setValFuncQueryStr(paramNameIn, strParamValIn) {
    let strHref = window.location.href;
    if (!strParamValIn) {
      return strHref;
    }
    const regExpNew = new RegExp("([?&])" + paramNameIn + "=.*?(&|$)", "i");
    const strSplit = strHref.indexOf("?") !== -1 ? "&" : "?";
    let strReturnResult = "";
    if (strHref.match(regExpNew)) {
      strReturnResult = strHref.replace(regExpNew, "$1" + paramNameIn + "=" + strParamValIn + "$2");
    } else {
      strReturnResult = strHref + strSplit + paramNameIn + "=" + strParamValIn;
    }
    window.history.replaceState({ path: strReturnResult }, "", strReturnResult);
  }
  // 针对 JSON 字符串过滤符号.
  static strFuncJsonFilter(strIn, boolActionId) {
    if (strIn === undefined || typeof strIn === "object") {
      return "";
    } else {
      if (boolActionId) {
        return strIn.replaceAll(":", "PlaceholderColon").replaceAll(",", "PlaceholderComma").replaceAll('"', "PlaceholderQuote");
      } else {
        return strIn.replaceAll("PlaceholderColon", ":").replaceAll("PlaceholderComma", ",").replaceAll("PlaceholderQuote", '"');
      }
    }
  }
  static boolFuncJsonExistChk(jsonTarget, strKey) {
    if (jsonTarget === undefined || jsonTarget === null || Object.keys(jsonTarget).length === 0) {
      return false;
    } else {
      return jsonTarget.hasOwnProperty.call(jsonTarget, strKey);
    }
  }
  static domFuncAncestorElem(SE05N8, ES02N8) {
    if (SE05N8 !== null) {
      while (typeof SE05N8.matches === "function" && !SE05N8.matches(ES02N8)) {
        if (SE05N8.tagName === "HTML") {
          SE05N8 = null;
          break;
        } else {
          SE05N8 = SE05N8.parentNode;
        }
      }
    }
    return SE05N8;
  }
  static strFuncCodeVerifyToken(strAuthPolicy, statusCode) {
    // If only user authentication is performed, a special message is generated. Otherwise, the message generated by the actual business is used.
    let statusCodeInner = statusCode;
    if (strAuthPolicy === "Open" && statusCode === "SuccOpen") {
      statusCodeInner = "ValidAT060";
    } else if (strAuthPolicy === "US040" && statusCode === "CofoUS040") {
      statusCodeInner = "ValidAT060";
    } else if (strAuthPolicy === "AG010") {
      if (statusCode === "SuccAG010") {
        statusCodeInner = "ValidAT060";
      } else if (statusCode === "ForbidAG010") {
        statusCodeInner = "ForbidAG010";
      }
    }
    return statusCodeInner;
  }
  static cssFuncTab(ObjTargetMenuIn, exprSelectorTargetDetailIn, followUpFuncIn) {
    let nodeListTargetMenu = null;
    if (typeof ObjTargetMenuIn === "string") {
      nodeListTargetMenu = document.querySelectorAll(ObjTargetMenuIn);
    } else {
      nodeListTargetMenu = ObjTargetMenuIn;
    }
    let nodeListTargetMenu2 = nodeListTargetMenu;
    if (nodeListTargetMenu !== null && nodeListTargetMenu.length > 0) {
      nodeListTargetMenu.forEach(function (srcElemCurrentMenuIn) {
        srcElemCurrentMenuIn.addEventListener("click", function () {
          //var EventWinw0 = window.event || e, SE05Tab2 = EventWinw0.srcElement || EventWinw0.target;
          // let NL01TargetM2 = null;
          // if (typeof ObjTargetMenuIn == 'string') {
          //   NL01TargetM2 = document.querySelectorAll(ObjTargetMenuIn);
          // } else {
          //   NL01TargetM2 = ObjTargetMenuIn;
          // }
          if (nodeListTargetMenu2 !== null) {
            nodeListTargetMenu2.forEach(function (srcElemTargetMenuIn) {
              if (srcElemTargetMenuIn.classList.contains("AuxiMarkCurrentTab18")) {
                srcElemTargetMenuIn.classList.remove("AuxiMarkCurrentTab18");
              }
            });
          }
          srcElemCurrentMenuIn.classList.add("AuxiMarkCurrentTab18");
          if (srcElemCurrentMenuIn.getAttribute("eg010") !== null) {
            //关闭所有同组元素.
            const nodeListTargetDetail = document.querySelectorAll(exprSelectorTargetDetailIn + '[eg010="' + srcElemCurrentMenuIn.getAttribute("eg010") + '"]');
            if (nodeListTargetDetail != null) {
              nodeListTargetDetail.forEach(function (srcElemTargetDetailIn) {
                HelperCore.cssFuncHide(srcElemTargetDetailIn);
              });
            }
          }
          const elemCurrentDetail = document.querySelector(exprSelectorTargetDetailIn + '[ei020="' + srcElemCurrentMenuIn.getAttribute("ei020") + '"]');
          if (elemCurrentDetail !== null) {
            setTimeout(function () {
              HelperCore.cssFuncShow(elemCurrentDetail);
              followUpFuncIn(srcElemCurrentMenuIn, elemCurrentDetail);
            }, 200);
          }
        });
      });
    }
  }
  static cssFuncHide(objElemIn) {
    if (typeof objElemIn == "string") {
      const nodeListSrc = document.querySelectorAll(objElemIn);
      if (nodeListSrc !== null) {
        nodeListSrc.forEach(function (srcElemIn) {
          if (srcElemIn !== null) {
            if (!srcElemIn.classList.contains("AuxiMarkHide")) {
              srcElemIn.classList.add("AuxiMarkFade00");
              setTimeout(function () {
                //执行后续事件.
                srcElemIn.classList.remove("AuxiMarkFade00");
                srcElemIn.classList.add("AuxiMarkHide");
              }, 200);
            }
          }
        });
      }
    } else {
      if (objElemIn !== null && !objElemIn.classList.contains("AuxiMarkHide")) {
        objElemIn.classList.add("AuxiMarkFade00");
        setTimeout(function () {
          //执行后续事件.
          objElemIn.classList.remove("AuxiMarkFade00");
          objElemIn.classList.add("AuxiMarkHide");
        }, 200);
      }
    }
  }
  //显示元素.
  static cssFuncShow(objElemIn) {
    if (typeof objElemIn == "string") {
      const nodeListSrc = document.querySelectorAll(objElemIn);
      if (nodeListSrc != null) {
        nodeListSrc.forEach(function (srcElemIn) {
          if (srcElemIn != null && srcElemIn.classList.contains("AuxiMarkHide")) {
            srcElemIn.classList.remove("AuxiMarkHide");
            srcElemIn.classList.add("AuxiMarkFade08");
            setTimeout(function () {
              //执行后续事件.
              srcElemIn.classList.remove("AuxiMarkFade08");
            }, 200);
          }
        });
      }
    } else {
      if (objElemIn !== null && objElemIn.classList.contains("AuxiMarkHide")) {
        objElemIn.classList.add("AuxiMarkFade08");
        objElemIn.classList.remove("AuxiMarkHide");
        setTimeout(function () {
          //执行后续事件.
          objElemIn.classList.remove("AuxiMarkFade08");
        }, 200);
      }
    }
  }
  static jsonFuncTokenPayload(strTokenIn) {
    const strArrayToken = strTokenIn.split(".");
    const jsonStrPayload = window.atob(decodeURIComponent(strArrayToken[1]));
    console.log(jsonStrPayload);
    return JSON.parse(jsonStrPayload);
  }
  // Debounce (防抖): 每次触发事件时设置延迟调用函数，在此期间取消以前触发的事件.
  static handleDebounce(funcFollowIn, numDelayIn) {
    let timerInner = null;
    return (...args) => {
      if (timerInner) clearTimeout(timerInner);
      timerInner = setTimeout(() => {
        funcFollowIn.apply(this, args);
      }, numDelayIn);
    };
  }
  // Throttle (节流): 事件占用一个时间段, 在此时间段内不会再接受事件触发.
  static handleThrottle(funcFollowIn, numDelayIn) {
    let timerInner = null;
    return (...args) => {
      if (!timerInner) {
        timerInner = setTimeout(() => {
          funcFollowIn.apply(this, args);
          timerInner = null;
        }, numDelayIn);
      }
    };
  }
  // View Shield.
  static cssFuncMask(BoolAI05N8, NumIndexN8, ET01N8) {
    const ThisM0 = this;
    let DivShieldM0 = document.querySelector("div.CA02Shield18");
    if (DivShieldM0 !== null) {
      if (ThisM0.NumShieldEmphasisM0 > 0) {
        clearTimeout(ThisM0.NumShieldEmphasisM0);
        ThisM0.NumShieldEmphasisM0 = 0;
      }
      if (DivShieldM0.classList.contains("AM04Emphasis")) {
        DivShieldM0.classList.remove("AM04Emphasis");
      }
      if (ET01N8 === null) {
        DivShieldM0.innerHTML = "Please wait...";
      } else {
        DivShieldM0.innerHTML = ET01N8;
      }
      DivShieldM0.style.zIndex = NumIndexN8;
      if (BoolAI05N8) {
        ThisM0.cssFuncShow(DivShieldM0);
        ThisM0.NumShieldEmphasisM0 = setTimeout(function () {
          if (!DivShieldM0.classList.contains("AM04Emphasis")) {
            DivShieldM0.classList.add("AM04Emphasis");
          }
        }, 1000);
      } else {
        ThisM0.cssFuncHide(DivShieldM0);
      }
    }
  }
}
class HelperWebComm {
  static reqFuncAccessToken(URL_TargetIn, jsonReqParamIn, strMethodIn) {
    const accessToken = window.localStorage.getItem("AccessToken");
    if (accessToken === null) {
      return Promise.resolve(["NullAT060", ""]);
    } else {
      return this.reqFuncUniv(URL_TargetIn, { authorization: accessToken }, jsonReqParamIn, strMethodIn);
    }
  }
  static reqFuncUniv(URL_TargetIn, jsonReqHeaderIn, objReqParamBodyIn, strMethodIn) {
    const strMethodInner = strMethodIn.toUpperCase();
    let initVector = {
      method: strMethodInner,
      referrerPolicy: "no-referrer-when-downgrade",
      headers: {},
    };
    if (jsonReqHeaderIn !== null) {
      // initVector.headers = JSON.stringify(jsonReqHeaderIn);
      initVector.headers = jsonReqHeaderIn;
    }
    switch (strMethodInner) {
      case "GET":
      case "DELETE":
        if (objReqParamBodyIn !== null) {
          const JS01reqParamInner = typeof objReqParamBodyIn === "string" ? objReqParamBodyIn : JSON.stringify(objReqParamBodyIn);
          const strQuery = new URLSearchParams(JSON.parse(JS01reqParamInner)).toString();
          URL_TargetIn = URL_TargetIn + "?" + strQuery;
        }
        break;
      case "POST":
      case "PUT":
        if (objReqParamBodyIn !== null) {
          initVector.body = typeof objReqParamBodyIn === "string" ? objReqParamBodyIn : JSON.stringify(objReqParamBodyIn);
          initVector.headers["Content-Type"] = "application/json";
        }
        break;
    }
    const promiseRespResult = fetch(URL_TargetIn, initVector)
      .then((respResult) => {
        if (respResult.ok) {
          return respResult.text();
        } else {
          return "FailWebReq";
        }
      })
      .then((strRespResult) => {
        let strArrayRespResult = ["FailWebReq", ""];
        if (strRespResult !== "FailWebReq") {
          strArrayRespResult[0] = "SuccWebReq";
          strArrayRespResult[1] = strRespResult;
        }
        return strArrayRespResult;
      });
    return promiseRespResult;
  }
}
class HelperUserAccount {
  static handlerLogin() {
    window.location.href = ConfigBiz.jsonFuncOption().UI_OAuth.strURL + "/LV06UA010/UV04LP010?NumAI020=" + ConfigBiz.jsonFuncOption().AppInfo.NumAppId + "&LR01AT060=" + encodeURIComponent(ConfigBiz.URL_LocalFunc()) + "&FP03SC160=" + encodeURIComponent("/LayoutViewUserAccount/VerfyUserWebCmd");
  }
  static jsonFuncUserGroup(numUpdateModeIn) {
    const jsonStrUserGroup = sessionStorage.getItem("jsonArrayUserGroup");
    if (numUpdateModeIn === 3 || (numUpdateModeIn === 2 && jsonStrUserGroup === null)) {
      const promiseRespResult = HelperWebComm.reqFuncAccessToken(ConfigBiz.jsonFuncOption().API_Local.strURL + "/AttrUserAccount/QueryUserGroup", {}, "get").then((strArrayRespResult) => {
        let jsonArrayUserGroupReturn = null;
        if (strArrayRespResult[0] === "NullAT060") {
          alert("Please login again.");
          HelperUserAccount.handlerLogin();
        } else if (strArrayRespResult[0] === "SuccWebReq") {
          const jsonRespResult = JSON.parse(strArrayRespResult[1]);
          if (jsonRespResult.StatusCode === "SuccGoal") {
            sessionStorage.setItem("jsonArrayUserGroup", JSON.stringify(jsonRespResult.Payload.JsonArrayUserGroup));
            jsonArrayUserGroupReturn = jsonRespResult.Payload.JsonArrayUserGroup;
          } else if (jsonRespResult.StatusCode === "OverdueVT030") {
            alert(jsonRespResult.Msg);
            HelperUserAccount.handlerLogin();
          }
        }
        return jsonArrayUserGroupReturn;
      });
      return promiseRespResult;
    } else if (jsonStrUserGroup === null) {
      return Promise.resolve(null);
    } else {
      return Promise.resolve(JSON.parse(jsonStrUserGroup));
    }
  }
  static jsonFuncCurrentUserGroup() {
    return this.jsonFuncUserGroup(2).then((jsonArrayUserGroupIn) => {
      let jsonReturnResult = { jsonArrayUserGroup: null, jsonCurrentUserGroup: null };
      if (jsonArrayUserGroupIn.length > 0) {
        jsonReturnResult.jsonArrayUserGroup = jsonArrayUserGroupIn;
        const strCurrentUserGroupNum = sessionStorage.getItem("NumCurrentUserGroup");
        if (strCurrentUserGroupNum === null) {
          jsonReturnResult.jsonCurrentUserGroup = jsonArrayUserGroupIn[0];
        } else {
          const jsonArrayCurrentUserGroup = jsonArrayUserGroupIn.filter((jsonItem) => jsonItem.NG010 === Number(strCurrentUserGroupNum));
          if (jsonArrayCurrentUserGroup.length > 0) {
            jsonReturnResult.jsonCurrentUserGroup = jsonArrayCurrentUserGroup[0];
          } else {
            jsonReturnResult.jsonCurrentUserGroup = jsonArrayUserGroupIn[0];
            sessionStorage.removeItem("NumCurrentUserGroup");
          }
        }
      }
      return jsonReturnResult;
    });
  }
}
class DataModelDataGroup {
  static jsonFuncSystemMgt(numUpdateModeIn, numCurrentUserIn) {
    const jsonStrDataGroupInner = sessionStorage.getItem("jsonDataGroupSystemMgt");
    // const strCurrentUserGroupNum = window.localStorage.getItem("CG040");
    let jsonDataGroupInner = jsonStrDataGroupInner === null ? null : JSON.parse(jsonStrDataGroupInner);
    const StrKeyM0 = "NG01-" + numCurrentUserIn;
    if (numUpdateModeIn === 3 || (numUpdateModeIn === 2 && (jsonDataGroupInner === null || !HelperCore.boolFuncJsonExistChk(jsonDataGroupInner, StrKeyM0)))) {
      let promiseDataGroupInner = HelperWebComm.reqFuncAccessToken(ConfigBiz.jsonFuncOption().API_Local.strURL + "/DataAccessWithGroup/QueryDataGroup", { CurrentUserGroup: numCurrentUserIn }, "get").then((strArrayRespResult) => {
        if (strArrayRespResult[0] === "SuccWebReq") {
          const jsonRespResult = JSON.parse(strArrayRespResult[1]);
          let statusCodeInner = HelperCore.strFuncCodeVerifyToken("US040", jsonRespResult.SC120);
          if (statusCodeInner === "SuccGoal") {
            if (jsonRespResult.Payload.length > 0) {
              if (jsonDataGroupInner === null) {
                jsonDataGroupInner = {};
              }
              jsonDataGroupInner[StrKeyM0] = jsonRespResult.Payload;
              sessionStorage.setItem("jsonDataGroupSystemMgt", JSON.stringify(jsonDataGroupInner));
            }
            return jsonDataGroupInner[StrKeyM0];
          } else {
            alert("Please login again.");
            HelperUserAccount.handlerLogin();
          }
        } else {
          return null;
        }
      });
      return promiseDataGroupInner;
    } else if (jsonDataGroupInner !== null && HelperCore.boolFuncJsonExistChk(jsonDataGroupInner, StrKeyM0)) {
      return Promise.resolve(jsonDataGroupInner[StrKeyM0]);
    } else {
      return Promise.resolve(null);
    }
  }
}
export { HelperCore, HelperWebComm, HelperUserAccount, DataModelDataGroup };
